/******************************************************************************
 * @File name   :      IMaintainDealerEmployeeServiceImpl.java
 *
 * @Author      :      chenggong jiang
 *
 * @Date        :      2011-6-21
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who                 Version        Comments
 * 2011-6-21 下午01:59:37     chenggong jiang     1.0            Initial Version
 * 2011-9-27 下午15:16:37    pxwu     1.1          update method getMaintainDealerEmployeeByIdvalidateCertificateCode
 * 2011-9-27 下午17:52:37    pxwu     1.2          update method validateCertificateCode
 * 2011-10-10 下午13:52:37    tun.tan     2.0      throw exception with error code
 * 2011-10-19 下午02:47:22 wangzhize       1.2        employeeinfo int to Integer ,fix type mismatch error
 * 2011-11-12  wangzhize       1.2        fix photo url moudle
 * 2011-11-14  wangzhize       1.2        fix issgm = 2
 *****************************************************************************/
package com.cap.bts.framework.dm.employeemgnt.service.impl;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cap.bts.commonfunc.cache.service.IResetCacheService;
import com.cap.bts.framework.approvalrule.constants.ApplicationTypeConstants;
import com.cap.bts.framework.approvalrule.constants.ApprovalCategoryConstants;
import com.cap.bts.framework.approvalrule.constants.ApprovalResult;
import com.cap.bts.framework.approvalrule.constants.ApprovalStatus;
import com.cap.bts.framework.approvalrule.service.IApprovalRuleService;
import com.cap.bts.framework.approvalrule.util.ApprovalRuleUtil;
import com.cap.bts.framework.codemapping.service.ICodeMapping;
import com.cap.bts.framework.common.constant.CommonConstants;
import com.cap.bts.framework.common.constant.CommonErrorConstants;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.service.impl.BaseServiceImpl;
import com.cap.bts.framework.common.util.BeanCopyUtil;
import com.cap.bts.framework.common.util.CodeTextUtils;
import com.cap.bts.framework.common.util.FileUtils;
import com.cap.bts.framework.common.util.Utils;
import com.cap.bts.framework.dm.approval.constant.UserGroupConstants;
import com.cap.bts.framework.dm.approval.dao.IDealerUsrGrpApprovalDao;
import com.cap.bts.framework.dm.approval.domain.UserGroupApplication;
import com.cap.bts.framework.dm.approval.dto.UserAccountApprovalDto;
import com.cap.bts.framework.dm.employeemgnt.constants.EmployeeUserAccountConstants;
import com.cap.bts.framework.dm.employeemgnt.constants.EmployeemgntConstants;
import com.cap.bts.framework.dm.employeemgnt.dao.ITempOrganizationUserDao;
import com.cap.bts.framework.dm.employeemgnt.dao.ITempUserUsrGrpDao;
import com.cap.bts.framework.dm.employeemgnt.domain.TempOrganizationUser;
import com.cap.bts.framework.dm.employeemgnt.domain.TempUserUsrGrp;
import com.cap.bts.framework.dm.employeemgnt.dto.MaintainEmployeeResultDto;
import com.cap.bts.framework.dm.employeemgnt.dto.MaintainEmployeeSubmitDto;
import com.cap.bts.framework.dm.employeemgnt.dto.UserGroupOrgDto;
import com.cap.bts.framework.dm.employeemgnt.service.IMaintainDealerEmployeeService;
import com.cap.bts.framework.dm.employeemgnt.utils.EmployeeMgntUtil;
import com.cap.bts.framework.ge.resetpassword.service.IResetPasswordService;
import com.cap.bts.framework.usermgnt.constant.AccountStatus;
import com.cap.bts.framework.usermgnt.constant.EmployeeStatus;
import com.cap.bts.framework.usermgnt.constant.ExportType;
import com.cap.bts.framework.usermgnt.constant.ResignCompleted;
import com.cap.bts.framework.usermgnt.constant.UserGroupCode;
import com.cap.bts.framework.usermgnt.constant.UserMgntConstants;
import com.cap.bts.framework.usermgnt.constant.UserStatus;
import com.cap.bts.framework.usermgnt.constant.UserType;
import com.cap.bts.framework.usermgnt.dao.IEmployeeInfoDao;
import com.cap.bts.framework.usermgnt.dao.IOrganizationDao;
import com.cap.bts.framework.usermgnt.dao.IOrganizationUserDao;
import com.cap.bts.framework.usermgnt.dao.IRoleDao;
import com.cap.bts.framework.usermgnt.dao.IUserDao;
import com.cap.bts.framework.usermgnt.dao.IUserGroupDao;
import com.cap.bts.framework.usermgnt.dao.IUserGroupRoleDao;
import com.cap.bts.framework.usermgnt.dao.IUserRoleDao;
import com.cap.bts.framework.usermgnt.dao.IUserUsrGrpDao;
import com.cap.bts.framework.usermgnt.domain.EmployeeInfo;
import com.cap.bts.framework.usermgnt.domain.Organization;
import com.cap.bts.framework.usermgnt.domain.OrganizationUser;
import com.cap.bts.framework.usermgnt.domain.Role;
import com.cap.bts.framework.usermgnt.domain.User;
import com.cap.bts.framework.usermgnt.domain.UserGroup;
import com.cap.bts.framework.usermgnt.domain.UserGroupRole;
import com.cap.bts.framework.usermgnt.domain.UserRole;
import com.cap.bts.framework.usermgnt.domain.UserUsrGrp;
import com.cap.bts.framework.usermgnt.dto.ApprovalSubmitDto;
import com.cap.bts.framework.usermgnt.dto.QueryEmployeeDto;
import com.cap.bts.framework.usermgnt.dto.UserDto;
import com.cap.bts.framework.usermgnt.service.IEmployeeInfoService;
import com.cap.bts.framework.usermgnt.service.IOrganizationMgntService;
import com.cap.bts.framework.usermgnt.service.IUserMgntService;
import com.cap.bts.framework.usermgnt.util.PasswordUtil;


/**
 *
 */
@Transactional(rollbackFor = AppException.class)
@Service
public class MaintainDealerEmployeeServiceImpl extends BaseServiceImpl implements
    IMaintainDealerEmployeeService {

    
    @Resource(name = "employeeInfoDao")
    private IEmployeeInfoDao employeeInfoDao;
    @Resource(name = "userUsrGrpDao")
    private IUserUsrGrpDao userUsrGrpDao;
    @Resource(name = "organizationUserDao")
    private IOrganizationUserDao organizationUserDao;
    @Resource(name = "tempOrganizationUserDao")
    private ITempOrganizationUserDao tempOrganizationUserDao;
    @Resource(name = "tempUserUsrGrpDao")
    private ITempUserUsrGrpDao tempUserUsrGrpDao;
    @Resource(name = "userDao")
    private IUserDao userDao;
    @Resource(name = "userGroupDao")
    private IUserGroupDao userGroupDao;
    @Resource(name = "organizationDao")
    private IOrganizationDao organizationDao;
    @Resource(name = "codeMappingImpl")
    private ICodeMapping codeMapping;
    @Resource(name = "userGroupRoleDao")
    IUserGroupRoleDao userGroupRoleDao;
    @Resource(name = "userRoleDao")
    IUserRoleDao userRoleDao;
    @Resource(name = "roleDao")
    private IRoleDao roleDao;
    @Autowired
    IResetPasswordService resetPasswordService;
   // @Resource(name = "dealerService")
    //private IDealerService dealerService;
    @Autowired
    private IOrganizationMgntService organizationMgntService;

    @Autowired
    private IUserMgntService userMgntService;
    @Autowired
    private IOrganizationMgntService orgMgntService;

    @Resource(name = "employeeInfoServiceImpl")
    private IEmployeeInfoService employeeService;
    
    @Autowired
    private ICodeMapping codeMappingService;
    
    @Resource(name = "resetCacheService")
    private IResetCacheService resetCacheService;
    

	@Resource(name = "dealerUsrGrpApprovalDao")
	private IDealerUsrGrpApprovalDao userGroupApplicationDao;
    
	@Resource(name = "approvalRuleServiceImpl")
	private IApprovalRuleService approvalRuleService;
	
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    
    
	private void syncEmployee() throws AppException{

		UserAccountApprovalDto dto=new UserAccountApprovalDto();
		dto.setUserCode("D00001");
		dto.setUserGroupCode("salesmanager");
		dto.setAppResult(1);
		dto.setOrgCode("CD1000");
		syncEmployeeByApprovalResult(dto,1);
		//operationType==1
	}

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : 2011-6-21
     * @see com.cap.bts.dms.dm.approval.IMaintainDealerEmployeeService#syncEmployeeByAoorovalResult(com.cap.bts.dms.dm.approval.dto.UserAccountApprovalDto)
     **/
    @Override
    public boolean syncEmployeeByApprovalResult(UserAccountApprovalDto userAccountApprovalDto,
        int operationType) throws AppException {
        if (userAccountApprovalDto != null) {
            User user = userMgntService.getUserByUserCode(userAccountApprovalDto.getUserCode());
            if (user != null) {
                EmployeeInfo employeeInfo = employeeInfoDao
                    .getEmployeeInfoByUserCode(userAccountApprovalDto.getUserCode());
                UserGroup newUserGroup = userGroupDao.getUserGroupByCode(userAccountApprovalDto
                    .getUserGroupCode());
                if (ApprovalResult.APPROVAL_AGREE == userAccountApprovalDto.getAppResult()) {// 通过审批
                    // 如果是新增用户
                    if (UserGroupConstants.CREATE_OPERATION_TYPE == operationType) {
                        userAccountApprovalDto.setEmploymentStatus(EmployeeStatus.NORMAL);
                        createUserData(userAccountApprovalDto);
                        // 获取岗位对应的角色，并生成新的USERROLE关联记录
                        updateUserRoleByGroup(user, newUserGroup);
                    }
                    // 如果是岗位变更
                    else if (UserGroupConstants.UPDATE_OPERATION_TYPE == operationType) {
                        userAccountApprovalDto.setEmploymentStatus(EmployeeStatus.NORMAL);
                        updateUserData(userAccountApprovalDto);
                        // 获取岗位对应的角色，删除原角色USERROLE记录并生成新的USERROLE关联记录
                        updateUserRoleByGroup(user, newUserGroup);
                    } else if (UserGroupConstants.UNREGISTER_OPERATION_TYPE == operationType) {
                        userAccountApprovalDto.setEmploymentStatus(EmployeeStatus.RESIGN);

                    }
                } else {// 未通过，审批拒绝
                    // 如果是新增用户
                    if (EmployeeStatus.PEND_TO_CREATE == employeeInfo.getEmploymentStatusId()) {
                        userAccountApprovalDto.setEmploymentStatus(EmployeeStatus.DRAFT);
                    } else {
                        userAccountApprovalDto.setEmploymentStatus(EmployeeStatus.NORMAL);
                    }
                    if (UserGroupConstants.CREATE_OPERATION_TYPE == operationType) {
                        tempOrganizationUserDao.deleteTempOrgUserOrgByUserId(user.getId());
                        tempUserUsrGrpDao.deleteTempUserUsrGrpByUserId(user.getId());
                    }
                    // 如果是岗位变更
                    else if (UserGroupConstants.UPDATE_OPERATION_TYPE == operationType) {
                        updateDataByTempData(user);
                        
                    }
                }
                // update employee status
                if (userAccountApprovalDto.getEmploymentStatus() > 0) {
                    employeeInfo
                        .setEmploymentStatusId(new Long(userAccountApprovalDto.getEmploymentStatus()));
                    employeeInfoDao.update(employeeInfo);
                    
                  if( UserGroupConstants.UNREGISTER_OPERATION_TYPE == operationType){
                    user = userMgntService.getUserByUserCode(employeeInfo.getUserCode());
                    user.setIsLocked(AccountStatus.LOCK.getValue());
                    user.setStatusCode(UserStatus.INACTIVE);
                    user.setLastUpdateDate(new Date());
                    userMgntService.updateUser(user);
                  }
                    
                    
                   
           
                }

                return true;
            }
        }
        return false;
    }

    /**
     * 
     * 
     * @Date : 2011-8-29
     * @param userAccountApprovalDto
     * @throws AppException
     */
    private void createUserData(UserAccountApprovalDto userAccountApprovalDto) throws AppException {
        User user = userMgntService.getUserByUserCode(userAccountApprovalDto.getUserCode());
        UserGroup newUserGroup = userGroupDao.getUserGroupByCode(userAccountApprovalDto.getUserGroupCode());
        Organization newOrganization = organizationDao
            .getOrganizationByOrgCode(userAccountApprovalDto.getOrgCode());

        tempOrganizationUserDao.deleteTempOrgUserOrgByUserId(user.getId());
        tempUserUsrGrpDao.deleteTempUserUsrGrpByUserId(user.getId());
        userUsrGrpDao.save(getUserUsrGrp(user.getId(), newUserGroup.getId()));
        organizationUserDao.save(getOrganizationUser(user.getId(), newOrganization.getId()));
    }

    /**
     * 
     * @Date : 2011-8-29
     */
    private void updateUserData(UserAccountApprovalDto userAccountApprovalDto) throws AppException {

        User user = userMgntService.getUserByUserCode(userAccountApprovalDto.getUserCode());
        TempOrganizationUser temporganizationUser = tempOrganizationUserDao
            .getTempOrgUsersByUserId(user.getId());
        TempUserUsrGrp tempUserUsrGrp = tempUserUsrGrpDao
            .getTempUserUsrGroupsByUserId(user.getId());

        tempOrganizationUserDao.deleteTempOrgUserOrgByUserId(user.getId());
        tempUserUsrGrpDao.deleteTempUserUsrGrpByUserId(user.getId());
        // if(temporganizationUser!=null){
        organizationUserDao.deleteOrganizationUserByUserCode(user.getUserCode());
        organizationUserDao.save(getOrganizationUser(user.getId(), temporganizationUser.getId()));
        // }
        // if(tempUserUsrGrp!=null){
        userUsrGrpDao.deleteUserUsrGrpByUsrCode(user.getUserCode());
        userUsrGrpDao.save(getUserUsrGrp(user.getId(), tempUserUsrGrp.getId()));
        // }

    }

    /**
     * 
     * @Date : 2011-6-22
     * @param user
     * @param userGroup
     * @param organization
     * @throws AppException
     */
    private void updateDataByTempData(User user) throws AppException {
        TempOrganizationUser temporganizationUser = tempOrganizationUserDao
            .getTempOrgUsersByUserId(user.getId());
        TempUserUsrGrp tempUserUsrGrp = tempUserUsrGrpDao
            .getTempUserUsrGroupsByUserId(user.getId());
// 取组织结构
        List<Organization> olist = organizationMgntService.getOrganizationsByUserCode(user
            .getUserCode());
        Organization organization = null;
        //判断 织结构是否存在
        if (olist != null && olist.size() > 0) {
            organization = olist.get(0);
            if (temporganizationUser != null) {
                temporganizationUser.setOrganizationId(organization.getId());
                tempOrganizationUserDao.update(temporganizationUser);
            }
        }
        //取用户组
        List<UserGroup> ulist = userMgntService.getUserGroupByUserCode(user.getUserCode());
        UserGroup userGroup = null;
      //判断 织结构是否存在 ， 存在保存
        if (ulist != null && ulist.size() > 0) {
            userGroup = ulist.get(0);
            if (tempUserUsrGrp != null) {
                tempUserUsrGrp.setUserGroupId(userGroup.getId());
                tempUserUsrGrpDao.update(tempUserUsrGrp);
            }
        }
    }

    /**
     * 生成新的用户岗位记录
     * 
     * @Date : 2011-6-21
     * @param userId
     * @param userGroupId
     * @return
     */
    private UserUsrGrp getUserUsrGrp(Long userId, Long userGroupId) {
        UserUsrGrp userUsrGrp = new UserUsrGrp();
        userUsrGrp.setUserGroupId(userGroupId);
        userUsrGrp.setUserId(userId);
        return userUsrGrp;
    }

    /**
     * 生成新的用户组织记录
     * 
     * @Date : 2011-6-21
     * @param userId
     * @param organizationId
     * @return
     */
    private OrganizationUser getOrganizationUser(Long userId, Long organizationId) {
        OrganizationUser organizationUser = new OrganizationUser();
        organizationUser.setUserId(userId);
        organizationUser.setOrganizationId(organizationId);
        return organizationUser;
    }

    /**
     * 岗位更换后更新用户角色
     * 
     * @Date : 2011-6-22
     * @param user
     * @param userGroup
     */
    private void updateUserRoleByGroup(User user, UserGroup userGroup) {
        List<UserGroupRole> userGroupRoleList = userGroupRoleDao
            .getUserGroupRoleListByUserGroupAndBrand(userGroup.getId(), user.getBrandId()); //取用户组
        userRoleDao.deleteUserRolesByUserCode(user.getUserCode());
        UserRole userRole = null;
        
        for (UserGroupRole userGroupRole : userGroupRoleList) {
            userRole = new UserRole();
            userRole.setUser(user);
            userRole.setRole(userGroupRole.getRole());
            userRole.setIsDefaultRole(UserMgntConstants.USER_ROLE_DEAFAULT_NO);
            userRoleDao.save(userRole);
        }
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @throws AppException
     * @Date : 2011-6-27
     * @see com.cap.bts.dms.dm.employeemgnt.service.IMaintainDealerEmployeeService#getMaintainDealerEmployeeByDto(com.cap.bts.framework.usermgnt.dto.QueryEmployeeDto)
     **/
    @Override
    public List<MaintainEmployeeResultDto> getMaintainDealerEmployeeByDto(QueryEmployeeDto dto)
        throws AppException {

        List<EmployeeInfo> employeeInfoList = employeeInfoDao.getMaintainEmployeeinfoByDto(dto);
        List<MaintainEmployeeResultDto> employeeResultDtoList = new ArrayList<MaintainEmployeeResultDto>();
        MaintainEmployeeResultDto employeeResultDto = null;
        //设置 EmployeeInfo 信息
        for (int i = 0, size = employeeInfoList.size(); i < size; i++) {

            EmployeeInfo employeeInfo = employeeInfoList.get(i);
            employeeResultDto = new MaintainEmployeeResultDto();
            employeeResultDto.setId(employeeInfo.getId());
            employeeResultDto.setUserCode(employeeInfo.getUserCode());
            employeeResultDto.setUserName(employeeInfo.getEmployeeName());
            employeeResultDto.setMobilePhone(employeeInfo.getMobilePhone());
            employeeResultDto.setBirthDate(employeeInfo.getBirthDate());
            employeeResultDto.setAddress(employeeInfo.getAddress());
            employeeResultDto.setEmploymentStatus(CodeTextUtils.getText("Employee.WorkStatus",
                String.valueOf(employeeInfo.getEmploymentStatusId())));
            //MarriageId 不存在  则设置
            if (employeeInfo.getMarriageId() != null){
                
                employeeResultDto.setMarrige(codeMapping.getCodeValueById(employeeInfo.getMarriageId()));
            }
            //EducationId 不存在  则设置
            if (employeeInfo.getEducationId() != null){
                
                employeeResultDto.setEducation(codeMapping.getCodeValueById(employeeInfo.getEducationId()));
            }
            this.setEmployeeUserGroupAndOrg(employeeResultDto, employeeInfo.getUserCode());
            employeeResultDto.setEmploymentStatusId(employeeInfo.getEmploymentStatusId());
            User user = userMgntService.getUserByUserCode(employeeInfo.getUserCode());
            employeeResultDto.setUserId((user == null) ? 0L : user.getId());
            employeeResultDtoList.add(employeeResultDto);
        }

        return employeeResultDtoList;
    }

    private void setEmployeeUserGroupAndOrg(MaintainEmployeeResultDto employeeResultDto, String userCode) throws AppException{
        
         User user = userMgntService.getUserByUserCode(userCode);
         List<UserGroup> usergroupList = userGroupDao.getUserGroupByUserCode(userCode);
         if ((usergroupList != null) && (usergroupList.size() > 0)){
             //employeeResultDto.setRoleList(roleDao.getRolesByUserCode(userCode));
             employeeResultDto.setUserGroupList(usergroupList);
         }else{
             usergroupList = new ArrayList<UserGroup>(); 
             TempUserUsrGrp tempUserUsrGrp = tempUserUsrGrpDao.getTempUserUsrGroupsByUserId(user
                 .getId());
             if (tempUserUsrGrp != null) {
                 UserGroup userGroup = userGroupDao.findById(tempUserUsrGrp.getUserGroupId());
                 usergroupList.add(userGroup);
                 List<Role> roleList = roleDao.getRolesByUsrGrpCode(userGroup.getUserGroupCode(), user.getBrandId());
                 employeeResultDto.setRoleList(roleList);
                 employeeResultDto.setUserGroupList(usergroupList);
             }
         }
         
         List<Organization> orgList = organizationDao.getOrganizationsByUserCode(userCode);
         if ((orgList != null) && (orgList.size() > 0)){
             
             employeeResultDto.setOrgList(organizationDao
                 .getOrganizationsByUserCode(userCode));
         }else{
             orgList = new ArrayList<Organization>();
             TempOrganizationUser tempOrgUser = tempOrganizationUserDao
             .getTempOrgUsersByUserId(user.getId());
             if (tempOrgUser != null) {
                 Organization org = organizationDao.findById(tempOrgUser.getOrganizationId());
                 orgList.add(org);
                 employeeResultDto.setOrgList(orgList);
             }
         }
    }
    
    /**
     * 生成用户ID，如果重复，则多生成一次
     * @Date        :      Nov 28, 2011
     * @return
     * @throws AppException
     */
    private String generateUserCode() throws AppException {
        String userCode = EmployeeMgntUtil.createUserCode();
        while (userCode == null || userDao.getUserByUserCode(userCode) != null) { //重复了，再查一次
        	System.out.println("UserCode:" + userCode + " is duplicated! Try again.");
        	userCode = EmployeeMgntUtil.createUserCode();
        }
        return userCode;
    }
    
    /**
     * {@inheritDoc} overridden:
     * 
     * @throws IOException
     * @Date : 2011-6-28
     * @see com.cap.bts.dms.dm.employeemgnt.service.IMaintainDealerEmployeeService#saveEmployee(com.cap.bts.dms.dm.employeemgnt.dto.MaintainEmployeeSubmitDto)
     **/
    @Override
    public boolean saveEmployee(MaintainEmployeeSubmitDto employeeSubmitDto, User user, Long dealerId, String dealerCode)
        throws AppException, IOException {

        boolean result = true;

        long userId = user.getId();
        EmployeeInfo employeeInfo = new EmployeeInfo();
        BeanCopyUtil.copyProperties(employeeSubmitDto, employeeInfo);
//    ExportData  存在    设置ExportData
        if(employeeInfo.getExportData() == null){
            employeeInfo.setExportData(ExportType.CAN_NOT_EXPORT.getValue());
        }
        
        employeeInfo.setId(null);
        String userCode = generateUserCode();
        //取 userCode 
        if (userCode == null) {
            userCode = generateUserCode();
        }
        if (userCode == null) {
            throw new AppException(CommonErrorConstants.SYSTEM_ERROR, "userCode is duplicated");
        }
        
        employeeInfo.setUserCode(userCode);
        employeeInfo.setCertificateType(employeeSubmitDto.getCertificateId());
        employeeInfo.setCertificateNo(employeeSubmitDto.getCertificateCode());
        employeeInfo.setIsDeboardCompleted(ResignCompleted.NOTCOMPLETE.getValue());
        employeeInfo.setIsSgm(UserType.DEALER);
        try {
        	//BirthDate tBrandFirstServiceDate 存在 则转换
            employeeInfo.setBirthDate(df.parse(employeeSubmitDto.getBirthDateStr()));
            employeeInfo.setBrandFirstServiceDate(df.parse(employeeSubmitDto
                .getBrandFirstServiceDateStr()));
            employeeInfo.setOnboardDate(df.parse(employeeSubmitDto.getOnboardDateStr()));

            if (employeeSubmitDto.getDriverLicenseDateStr() != null) {
                employeeInfo.setDriverLicenseDate(df.parse(employeeSubmitDto
                    .getDriverLicenseDateStr()));
            }
            if (employeeSubmitDto.getPassTrainingDateStr() != null) {
                employeeInfo.setPassTrainingDate(df.parse(employeeSubmitDto
                    .getPassTrainingDateStr()));
            }

        } catch (ParseException e) {
            result = false;
            e.printStackTrace();
        }

        employeeInfo.setSaleConsultLevel(0L);
        employeeInfo.setBrandId(user.getBrandId());
        employeeInfo.setDealerId(dealerId);
//        employeeInfo.setEmployeeCode(EmployeeMgntUtil.createEmployeeCode());
        employeeInfo.setEmployeeCode(employeeSubmitDto.getEmployeeCode());
        employeeInfo.setCreateBy(userId);
        employeeInfo.setLastUpdateBy(userId);
        if (employeeSubmitDto.getOperationType() == EmployeemgntConstants.OPERATION_TYPE_SAVE) {

            employeeInfo.setEmploymentStatusId(new Long(EmployeeStatus.DRAFT));
        } else {
            employeeInfo.setEmploymentStatusId(new Long(EmployeeStatus.PEND_TO_CREATE));
        }

        // if (employeeSubmitDto.getOperationType() ==
        // EmployeemgntConstants.OPERATION_TYPE_SAVEANDSUBMIT) {

        // employeeInfo.setEmploymentStatusId(3L);
        // }
// 取下载路径
        String downloadUrl = "";
        if ((employeeSubmitDto.getPhotoFile() != null)
            && Utils.notEmpty(employeeSubmitDto.getPhotoFile().getOriginalFilename())) {

            downloadUrl = FileUtils.uploadFileForDealer(user.getEmployerOrg().getId(),
            		FileUtils.getValue(CommonConstants.EMPLOYEE_PHOTO_ODULE_NAME), employeeSubmitDto.getPhotoFile()
                    .getOriginalFilename(), employeeSubmitDto.getPhotoFile().getInputStream());
        }
        employeeInfo.setPhotoUrl(downloadUrl);
        employeeInfo.setIsTrainner(0);
        employeeInfoDao.save(employeeInfo);

        UserDto userDto = new UserDto();

        // Get the user input user group and organization
        List<UserGroupOrgDto> userGrpOrgDtos = employeeSubmitDto.getUserGroupOrgList();
        String defaultUserGroupCode = "";
        if (userGrpOrgDtos != null) {

            defaultUserGroupCode = userGrpOrgDtos.get(0).getUserGroupCode();

        }

       userDto.setDefaultUserGroupCode(defaultUserGroupCode);
        
        //设置信息
        userDto.setBrandId(employeeInfo.getBrandId());
        userDto.setUserType(UserType.DEALER);
        userDto.setEmployeeInfoId(employeeInfo.getId());
        userDto.setUserCode(employeeInfo.getUserCode());
        userDto.setEmployeeName(employeeInfo.getEmployeeName());
        userDto.setEmployerOrgId(user.getEmployerOrg().getId());
        String password = PasswordUtil.getRandom();
        userDto.setPassword(password);
        userDto.setOperatorId(userId);
        userMgntService.createUserByDto(userDto);

        User tempUser = userMgntService.getUserByUserCode(employeeInfo.getUserCode());
        employeeInfo.setUserId(tempUser.getId());
        employeeInfoDao.update(employeeInfo);
        
        UserGroupOrgDto usrgrpOrgDto = null;

        if (userGrpOrgDtos != null && userGrpOrgDtos.size() > 0) {

            TempOrganizationUser tempOrgUser = null;
            TempUserUsrGrp tempUserUsrGrp = null;
            for (int i = 0; i < userGrpOrgDtos.size(); i++) {
                usrgrpOrgDto = userGrpOrgDtos.get(i);
                UserGroup userGroup = userMgntService.getUserGroupByCode(usrgrpOrgDto
                    .getUserGroupCode());
                Organization organization = orgMgntService.getOrganizationByOrgCode(usrgrpOrgDto
                    .getOrgCode());
                if (organization != null) {
                    tempOrgUser = new TempOrganizationUser();
                    tempOrgUser.setUserId(tempUser.getId());
                    tempOrgUser.setOrganizationId(organization.getId());
                    tempOrgUser.setCreateBy(userId);
                    tempOrgUser.setLastUpdateBy(userId);
                    tempOrganizationUserDao.save(tempOrgUser);

                    tempUserUsrGrp = new TempUserUsrGrp();
                    tempUserUsrGrp.setCreateBy(userId);
                    tempUserUsrGrp.setLastUpdateBy(userId);
                    tempUserUsrGrp.setUserId(tempUser.getId());
                    tempUserUsrGrp.setUserGroupId(userGroup.getId());
                    tempUserUsrGrpDao.save(tempUserUsrGrp);

                }

            }
        }
		UserGroup userGroup = userGroupDao.getUserGroupByCode(usrgrpOrgDto.getUserGroupCode());
		Organization org = organizationDao.getOrganizationByOrgCode(usrgrpOrgDto.getOrgCode());
    	this.saveUserGroupApplication(userGroup, org, 3,
				employeeInfo, user,user);
       
        return result;
    }

	private void saveUserGroupApplication(UserGroup userGroup,
			Organization org, long brandId, EmployeeInfo employeeInfo,
			User operator,User user) throws AppException {
		// 用户组
		if (userGroup != null && org != null) {
			int appCategory = getUsrGrpApprovalCategory(
					userGroup.getUserGroupCode(),
					userGroup.getUserGroupLevel(), employeeInfo.getBrandId());
			UserGroupApplication userGroupApplication = new UserGroupApplication(
					(int) brandId, appCategory);
			userGroupApplication.setEmployeeInfo(employeeInfo);
			if (employeeInfo.getEmploymentStatusId() == EmployeeStatus.PEND_TO_CREATE) {
				userGroupApplication
						.setOperationType(EmployeeUserAccountConstants.USER_GROUP_APPLICATION_OPERATIONTYPE_ADD);// 设置结点类型
			} else if (employeeInfo.getEmploymentStatusId() == EmployeeStatus.PEND_TO_CHANGE) {
				userGroupApplication
						.setOperationType(EmployeeUserAccountConstants.USER_GROUP_APPLICATION_OPERATIONTYPE_UPDATE);// 设置结点类型
			}
			Organization applicationOrg = organizationDao
					.getOrganizationByOrgCode(org.getOwnerId());
			userGroupApplication.setOrgCode(org.getOrgCode());
			userGroupApplication.setDealerOrgId(applicationOrg.getId());
			userGroupApplication.setResult(ApprovalStatus.NOT_APPROVAL);
			userGroupApplication.setUsrgrpCode(userGroup.getUserGroupCode());
			userGroupApplication.setCreateBy(operator.getId());
			userGroupApplication.setLastUpdateBy(operator.getId());
			if(user!=null && user.getUserGroup()!=null){
				userGroupApplication.setSrcGrpCode(user.getUserGroup().getUserGroupCode());
			}
			userGroupApplicationDao.save(userGroupApplication);
			String startStepCode = ApprovalRuleUtil.getRuleStartPoint(
					(int) brandId, appCategory);
			approvalRuleService.createStartRuleSteps(userGroupApplication,
					userGroupApplication.getId(),
					ApplicationTypeConstants.USERGROUP_APPLICATION_TYPE,
					startStepCode);
		}
	}
	
	
	private static int getUsrGrpApprovalCategory(String userGroupCode,
			int level, Long brandId) {

		//  没有自己的审批流程是关键岗位
		// 有自己审批岗位就用自己，没有就用1：普通岗位。2：关键岗位
		if (UserGroupCode.GMCODE.getValue().equals(userGroupCode)) {// 总经理有自己审批流程
			return ApprovalCategoryConstants.KEY_STATION;
		} else {// 非关键岗位
			return ApprovalCategoryConstants.NORMAL_STATION;
		}
	}
    /**
     * {@inheritDoc} overridden:
     * 
     * @throws AppException
     * @Date : 2011-6-29
     * @see com.cap.bts.dms.dm.employeemgnt.service.IMaintainDealerEmployeeService#MaintainDealerEmployeeById(long)
     **/
    @Override
    public MaintainEmployeeSubmitDto getMaintainDealerEmployeeById(long employeeId)
        throws AppException {

        EmployeeInfo employeeInfo = employeeService.getEmployeeInfoById(employeeId);
        MaintainEmployeeSubmitDto employeeSubmitDto = new MaintainEmployeeSubmitDto();
        BeanCopyUtil.beanCopyProperties(employeeInfo, employeeSubmitDto);
        employeeSubmitDto.setCertificateId(employeeInfo.getCertificateType());
        employeeSubmitDto.setCertificateCode(employeeInfo.getCertificateNo());
        
        //设置ResignCompleted
        if (employeeInfo.getIsDeboardCompleted() == null){
            employeeSubmitDto.setIsDeboardCompleted(ResignCompleted.NOTCOMPLETE.getValue());
        }
        employeeSubmitDto.setBirthDateStr(employeeInfo.getBirthDate() != null ? df
            .format(employeeInfo.getBirthDate()) : "");
        employeeSubmitDto
            .setBrandFirstServiceDateStr(employeeInfo.getBrandFirstServiceDate() == null ? "" : df
                .format(employeeInfo.getBrandFirstServiceDate()));
        employeeSubmitDto.setDriverLicenseDateStr(employeeInfo.getDriverLicenseDate() == null ? ""
            : df.format(employeeInfo.getDriverLicenseDate()));
        employeeSubmitDto.setOnboardDateStr(employeeInfo.getOnboardDate() == null ? "" : df
            .format(employeeInfo.getOnboardDate()));
        employeeSubmitDto.setPassTrainingDateStr(employeeInfo.getPassTrainingDate() == null ? ""
            : df.format(employeeInfo.getPassTrainingDate()));
        //图片路径
        String photoUrl = FileUtils.getDownloadUrl(FileUtils
            .getValue(CommonConstants.EMPLOYEE_PHOTO_ODULE_NAME), employeeInfo.getPhotoUrl());
        employeeSubmitDto.setPhotoUrl(photoUrl);
        User user = userDao.getUserByUserCode(employeeInfo.getUserCode());
       // employeeSubmitDto.setUserGroupOrgList(getUserGroupOrgDto(user));

        return employeeSubmitDto;
    }

    /**
     * 根据条件得到 UserGroupOrgDto
     * 
     * @Date : 2011-6-29
     * @param userCode
     *            String
     * @param defaultUserGroupCode
     *            String
     * @param ownerId
     *            String
     * @return List<UserGroupOrgDto>
     * @throws AppException
     */
    private List<UserGroupOrgDto> getUserGroupOrgDto(User user) throws AppException {

        List<Organization> orgList = orgMgntService.getOrganizationsByUserCode(user.getUserCode());
        List<UserGroup> userGroupList = userGroupDao.getUserGroupByUserCode(user.getUserCode());
        Organization org = null;
        UserGroup userGroup = null;
        
        //设置用户组
        if ((userGroupList != null) && (userGroupList.size() > 0)){
         
            userGroup = userGroupList.get(0);
            
        }else{
            TempUserUsrGrp tempUserUsrGrp = tempUserUsrGrpDao.getTempUserUsrGroupsByUserId(user
                .getId());
            if (tempUserUsrGrp != null) {
                userGroup = userGroupDao.findById(tempUserUsrGrp.getUserGroupId());
            }
        }
      //设置组织结构
        if ((orgList != null) && (orgList.size() > 0)){
            
            org = orgList.get(0);
        }else{
            TempOrganizationUser tempOrgUser = tempOrganizationUserDao
            .getTempOrgUsersByUserId(user.getId());
            if (tempOrgUser != null) {
                org = organizationDao.findById(tempOrgUser.getOrganizationId());
            }
        }
        
        if (userGroup == null){
            throw new AppException(CommonErrorConstants.COMMON_USER_IS_NOT_USERGROUP, "the user not has userGroup");
        }
        if (org == null){
            throw new AppException(CommonErrorConstants.COMMON_USER_IS_NOT_ORGANIZATION, "the user not has Organization ");
        }
        
        //设置组织结构附件点
        String parentOrgCode = org.getParentOrgCode();
        Organization parentOrg = null;
        if (Utils.notEmpty(parentOrgCode)){
             parentOrg = orgMgntService.getOrganizationByOrgCode(parentOrgCode);
        }
        List<UserGroupOrgDto> userGroupOrgDtoList = new ArrayList<UserGroupOrgDto>();
        List<User> users = orgMgntService.getManagerUserByOrgCodeAndUsrGrpCode(userGroup
            .getUserGroupCode(), org.getOrgCode());
        //设置用户
        StringBuilder userStr = new StringBuilder();
        if (users != null && users.size() > 0) {
            for (int i = 0; i < users.size(); i++) {
                User userTemp = users.get(i);
                userStr.append(userTemp.getName() + ",");
            }
            if (userStr.length() > 0) {
                userStr.deleteCharAt(userStr.length() - 1);
            }
        }

        UserGroupOrgDto userGroupOrgDto = new UserGroupOrgDto();
        userGroupOrgDto.setUserGroupCode(userGroup.getUserGroupCode());
        userGroupOrgDto.setUserGroupName(userGroup.getUserGroupName());
        userGroupOrgDto.setDefUserGroupName(userGroup.getUserGroupName());
        userGroupOrgDto.setOrgName(org.getOrgName());
        userGroupOrgDto.setOrgManager(userStr.toString());
        if (parentOrg != null) {

            userGroupOrgDto.setAdvancedOrgName(parentOrg.getOrgName());
        } else {
            userGroupOrgDto.setAdvancedOrgName("");
        }

        userGroupOrgDto.setOrgCode(org.getOrgCode());
        userGroupOrgDtoList.add(userGroupOrgDto);

        return userGroupOrgDtoList;
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @throws IOException
     * @Date : 2011-6-29
     * @see com.cap.bts.dms.dm.employeemgnt.service.IMaintainDealerEmployeeService#saveOrUpdateEmployeeInfoByDto(com.cap.bts.dms.dm.employeemgnt.dto.MaintainEmployeeSubmitDto)
     **/
    @Override
    public void saveOrUpdateEmployeeInfoByDto(MaintainEmployeeSubmitDto employeeSubmitDto, User operator, String dealerCode)
        throws AppException, IOException {
        String downloadUrl = null;
        User user = userDao.getUserByUserCode(employeeSubmitDto.getUserCode());

        if (employeeSubmitDto.getPhotoFile().getOriginalFilename().intern() != "") {

            downloadUrl = FileUtils.uploadFileForDealer(user.getEmployerOrg().getId(),
            		FileUtils.getValue(CommonConstants.EMPLOYEE_PHOTO_ODULE_NAME), employeeSubmitDto.getPhotoFile()
                    .getOriginalFilename(), employeeSubmitDto.getPhotoFile().getInputStream());
        }

        EmployeeInfo employeeInfo = employeeInfoDao.findById(employeeSubmitDto.getId());

        employeeInfo.setGenderId(employeeSubmitDto.getGenderId());
        employeeInfo.setMobilePhone(employeeSubmitDto.getMobilePhone());
        if(employeeSubmitDto.getExportData() != null){
            employeeInfo.setExportData(employeeSubmitDto.getExportData());
        }
        employeeInfo.setEmail(employeeSubmitDto.getEmail());
        employeeInfo.setCertificateType(employeeSubmitDto.getCertificateId());
        employeeInfo.setCertificateNo(employeeSubmitDto.getCertificateCode());
        employeeInfo.setMarriageId(employeeSubmitDto.getMarriageId());
        employeeInfo.setBirthPlace(employeeSubmitDto.getBirthPlace());
        employeeInfo.setEducationId(employeeSubmitDto.getEducationId());
        employeeInfo.setAddress(employeeSubmitDto.getAddress());
        employeeInfo.setIsBrandTraining(employeeSubmitDto.getIsBrandTraining());
        employeeInfo.setHasDriverLicense(employeeSubmitDto.getHasDriverLicense());
        employeeInfo.setLastUpdateDate(new Date());
        employeeInfo.setLastUpdateBy(employeeSubmitDto.getLastUpdateBy());

        try {
            employeeInfo.setBirthDate(df.parse(employeeSubmitDto.getBirthDateStr()));
            employeeInfo.setBrandFirstServiceDate(df.parse(employeeSubmitDto
                .getBrandFirstServiceDateStr()));
            employeeInfo.setOnboardDate(df.parse(employeeSubmitDto.getOnboardDateStr()));

            if (employeeSubmitDto.getDriverLicenseDateStr() != null) {
                employeeInfo.setDriverLicenseDate(df.parse(employeeSubmitDto
                    .getDriverLicenseDateStr()));
            }
            if (employeeSubmitDto.getPassTrainingDateStr() != null) {
                employeeInfo.setPassTrainingDate(df.parse(employeeSubmitDto
                    .getPassTrainingDateStr()));
            }

        } catch (ParseException e) {
           new AppException("Parse date exception", "parse date exception", e.getCause());
        }

        if (downloadUrl != null) {

            employeeInfo.setPhotoUrl(downloadUrl);
        }
        employeeInfoDao.update(employeeInfo);
        
//        //保存时判断，EmploymentStatus不为草稿时更新GDMS端EmployeeInfo
//        if( employeeInfo.getEmploymentStatusId() != null && employeeInfo.getEmploymentStatusId() != EmployeeStatus.DRAFT){
//            String url = WSRegPropertiesUtil
//                .getProperties(WebServiceRegisterConstant.GDMS_SERVICE_SERVICE_WS_URI);
//            try {
//                WSGdmsFacadeStub stub = new WSGdmsFacadeStub(url);
//                stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(WebServiceRegisterConstant.TIME_OUT);
//                WSGdmsFacadeStub.WSDealerEmployeeDto wSDealerEmployeeDto = new WSGdmsFacadeStub.WSDealerEmployeeDto();
//                wSDealerEmployeeDto.setBrandId(employeeInfo.getBrandId());
//                wSDealerEmployeeDto.setEmployeeCode(employeeInfo.getEmployeeCode());
//                wSDealerEmployeeDto.setUserCode(employeeInfo.getUserCode());
//                wSDealerEmployeeDto.setPhotoUrl(employeeInfo.getPhotoUrl());
//                wSDealerEmployeeDto.setUserName(employeeInfo.getEmployeeName());
//                wSDealerEmployeeDto.setEmail(employeeInfo.getEmail());
//                wSDealerEmployeeDto.setExportData(employeeInfo.getExportData());
//                CodeInfo certificateCodeInfo = codeMappingService.getCodeInfoById(employeeInfo.getCertificateType());
//                if(certificateCodeInfo != null){
//                    wSDealerEmployeeDto.setCertificateTypeCode(certificateCodeInfo.getCode());
//                }
//                wSDealerEmployeeDto.setCertificateCode(employeeInfo.getCertificateNo());
//                wSDealerEmployeeDto.setEmploymentStatusId(employeeInfo.getEmploymentStatusId());
//                CodeInfo genderCodeInfo = codeMappingService.getCodeInfoById(employeeInfo.getGenderId());
//                if(genderCodeInfo != null){
//                    wSDealerEmployeeDto.setGenderCode(genderCodeInfo.getCode());
//                }
//                CodeInfo marriageCodeInfo = codeMappingService.getCodeInfoById(employeeInfo.getMarriageId());
//                if(marriageCodeInfo != null){
//                    wSDealerEmployeeDto.setMarriageCode(marriageCodeInfo.getCode());
//                }
//                wSDealerEmployeeDto.setBirthPlace(employeeInfo.getBirthPlace());
//                if(employeeInfo.getBirthDate() != null){
//                    wSDealerEmployeeDto.setBirthDateStr(df.format(employeeInfo.getBirthDate()));
//                }
//                CodeInfo educationCodeInfo = codeMappingService.getCodeInfoById(employeeInfo.getEducationId());
//                if(educationCodeInfo != null){
//                    wSDealerEmployeeDto.setEducationCode(educationCodeInfo.getCode());
//                }
//                if(employeeInfo.getMobilePhone() != null){
//                    wSDealerEmployeeDto.setMobilePhone(String.valueOf(employeeInfo.getMobilePhone()));
//                }
//                wSDealerEmployeeDto.setAddress(employeeInfo.getAddress());
//                if(employeeInfo.getOnboardDate() != null){
//                    wSDealerEmployeeDto.setOnboardDateStr(df.format(employeeInfo.getOnboardDate()));
//                }
//                if(employeeInfo.getBrandFirstServiceDate() != null){
//                    wSDealerEmployeeDto.setBrandFirstServiceDateStr(df.format(employeeInfo.getBrandFirstServiceDate()));
//                }
//                wSDealerEmployeeDto.setIsBrandTraining(employeeInfo.getIsBrandTraining());
//                if (employeeInfo.getPassTrainingDate() != null){
//                    wSDealerEmployeeDto.setPassTrainingDateStr(df.format(employeeInfo.getPassTrainingDate()));
//                }
//                wSDealerEmployeeDto.setHasDriverLicense(employeeInfo.getHasDriverLicense());
//                if (employeeInfo.getDriverLicenseDate() != null){
//                    wSDealerEmployeeDto.setDriverLicenseDateStr(df.format(employeeInfo.getDriverLicenseDate()));
//                }
//                wSDealerEmployeeDto.setLastUpdateByCode(operator.getUserCode());
//                wSDealerEmployeeDto.setDealerCode(dealerCode);
//                
//                //GDMS端人员信息同步
//                WSGdmsFacadeStub.HandlerWSUserEmployeeApplication handlerWSUserEmployeeApplication = new WSGdmsFacadeStub.HandlerWSUserEmployeeApplication();
//                handlerWSUserEmployeeApplication.setArgs0(wSDealerEmployeeDto);
//                WSGdmsFacadeStub.HandlerWSUserEmployeeApplicationResponse response = stub.handlerWSUserEmployeeApplication(handlerWSUserEmployeeApplication);
//                boolean result = response.get_return();
//                if( !result) {
//                    throw new AppException(SysErrorCodes.SYS_WEBSERVICE_ERROR, "Syncornized Employee failed !");
//                }
//            } catch (Exception e) {
//                throw new AppException(SysErrorCodes.SYS_WEBSERVICE_ERROR, e.getLocalizedMessage());
//            }
//        }
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : 2011-6-29
     * @see com.cap.bts.dms.dm.employeemgnt.service.IMaintainDealerEmployeeService#saveOrUpdateUsrGrpAndOrgByDto(com.cap.bts.dms.dm.employeemgnt.dto.MaintainEmployeeSubmitDto)
     **/
    @Override
    public void saveOrUpdateUsrGrpAndOrgByDto(MaintainEmployeeSubmitDto employeeSubmitDto, User operator, Long dealerId, String dealerCode)
        throws AppException {}
    
    /**
     * 更新就业状态
     * @Date        :      2011-11-14
     * @param employeeInfo
     * @param employmentStatusId
     * @param operatorId
     * @throws AppException
     */
    private void updateEmploymentStatus(EmployeeInfo employeeInfo, int employmentStatusId, Long operatorId) throws AppException{
        
        employeeInfo.setEmploymentStatusId(new Long(employmentStatusId));
        employeeInfo.setLastUpdateBy(operatorId);
        employeeService.update(employeeInfo);
        
    }
  

    /**
     * 把用户信息封装成WEBSERVICE参数
     * @Date        :      2011-11-14
     * @param employeeInfo
     * @param wsDealerEmployeeDto
     * @param employeeSubmitDto
     * @param usrgrpOrgDto
     * @param operator
     * @param dealerCode
     * @throws AppException
     */
//    private void domainToWSDealerEmployeeDto(EmployeeInfo employeeInfo,
//        WSGdmsFacadeStub.WSDealerEmployeeDto wsDealerEmployeeDto,
//        MaintainEmployeeSubmitDto employeeSubmitDto, UserGroupOrgDto usrgrpOrgDto, User operator, String dealerCode) throws AppException {
//       
//        wsDealerEmployeeDto.setBrandId(employeeInfo.getBrandId());
//        wsDealerEmployeeDto.setEmployeeCode(employeeInfo.getEmployeeCode());
//        wsDealerEmployeeDto.setUserCode(employeeInfo.getUserCode());
//        wsDealerEmployeeDto.setPhotoUrl(employeeInfo.getPhotoUrl());
//        wsDealerEmployeeDto.setUserName(employeeInfo.getEmployeeName());
//        wsDealerEmployeeDto.setEmail(employeeInfo.getEmail());
//        wsDealerEmployeeDto.setExportData(employeeInfo.getExportData());
//        CodeInfo certificateCodeInfo = codeMappingService.getCodeInfoById(employeeInfo.getCertificateType());
//        if(certificateCodeInfo != null){
//        	wsDealerEmployeeDto.setCertificateTypeCode(certificateCodeInfo.getCode());
//        }
//        wsDealerEmployeeDto.setCertificateCode(employeeInfo.getCertificateNo());
//        //wsDealerEmployeeDto.setEmploymentStatusId(employeeInfo.getEmploymentStatusId());
//        CodeInfo genderCodeInfo = codeMappingService.getCodeInfoById(employeeInfo.getGenderId());
//        if(genderCodeInfo != null){
//        	wsDealerEmployeeDto.setGenderCode(genderCodeInfo.getCode());
//        }
//        CodeInfo marriageCodeInfo = codeMappingService.getCodeInfoById(employeeInfo.getMarriageId());
//        if(marriageCodeInfo != null){
//        	wsDealerEmployeeDto.setMarriageCode(marriageCodeInfo.getCode());
//        }
//        wsDealerEmployeeDto.setBirthPlace(employeeInfo.getBirthPlace());
//        if(employeeInfo.getBirthDate() != null){
//        	wsDealerEmployeeDto.setBirthDateStr(df.format(employeeInfo.getBirthDate()));
//        }
//        CodeInfo educationCodeInfo = codeMappingService.getCodeInfoById(employeeInfo.getEducationId());
//        if(educationCodeInfo != null){
//        	wsDealerEmployeeDto.setEducationCode(educationCodeInfo.getCode());
//        }
//        if(employeeInfo.getMobilePhone() != null){
//        	wsDealerEmployeeDto.setMobilePhone(String.valueOf(employeeInfo.getMobilePhone()));
//        }
//        wsDealerEmployeeDto.setAddress(employeeInfo.getAddress());
//        if(employeeInfo.getOnboardDate() != null){
//        	wsDealerEmployeeDto.setOnboardDateStr(df.format(employeeInfo.getOnboardDate()));
//        }
//        if(employeeInfo.getBrandFirstServiceDate() != null){
//        	wsDealerEmployeeDto.setBrandFirstServiceDateStr(df.format(employeeInfo.getBrandFirstServiceDate()));
//        }
//        wsDealerEmployeeDto.setIsBrandTraining(employeeInfo.getIsBrandTraining());
//        if (employeeInfo.getPassTrainingDate() != null){
//            wsDealerEmployeeDto.setPassTrainingDateStr(df.format(employeeInfo.getPassTrainingDate()));
//        }
//        wsDealerEmployeeDto.setHasDriverLicense(employeeInfo.getHasDriverLicense());
//        if (employeeInfo.getDriverLicenseDate() != null){
//            wsDealerEmployeeDto.setDriverLicenseDateStr(df.format(employeeInfo.getDriverLicenseDate()));
//        }
//        wsDealerEmployeeDto.setUserGroupCode(usrgrpOrgDto.getUserGroupCode());
//        wsDealerEmployeeDto.setOrgCode(usrgrpOrgDto.getOrgCode());
//        wsDealerEmployeeDto.setLastUpdateByCode(operator.getUserCode());
//        wsDealerEmployeeDto.setDealerCode(dealerCode);       
//    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : 2011-6-29
     * @see com.cap.bts.dms.dm.employeemgnt.service.IMaintainDealerEmployeeService#deleteEmployee(long)
     **/
    @Override
    public void deleteEmployee(long employeeId) throws AppException {

        EmployeeInfo employeeInfo = employeeInfoDao.findById(employeeId);
        User user = userMgntService.getUserByUserCode(employeeInfo.getUserCode());
        tempOrganizationUserDao.deleteTempOrgUserOrgByUserId(user.getId());
        tempUserUsrGrpDao.deleteTempUserUsrGrpByUserId(user.getId());
        userDao.remove(user);
        employeeInfoDao.remove(employeeInfo);
        resetCacheService.resetMenuCacheByUserCode(user.getUserCode());

    }

    /**
     * 注意:证件类型暂时不用
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2011-9-27
     * @see com.cap.bts.dms.dm.employeemgnt.service.IMaintainDealerEmployeeService#validateCertificateCode(java.lang.String, Long)
    **/
    @Override
    public String validateCertificateCode(String certificateCode, Long certificateType) throws AppException {
       
        String  result = employeeInfoDao.validateCertificateCode(certificateCode, certificateType);
        return result;
    }
    /**
     * 
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Aug 8, 2012
     * @see com.cap.bts.dms.dm.employeemgnt.service.IMaintainDealerEmployeeService#validateCertificateCodeForUpdate(java.lang.String, java.lang.Long, java.lang.String)
    *
     */
    @Override
    public boolean validateCertificateCodeForUpdate(String certificateCode,Long certificateType,String userCode) throws AppException {
       
    	List<EmployeeInfo> employees= employeeInfoDao.queryEmployeeByCertificateCode(certificateCode,certificateType);
    	if(null==employees){
    		return true;
    	}
    	if(employees.isEmpty()){
    		return true;
    	}
    	if(employees.size()>1){
    		return false;
    	}
    	EmployeeInfo employeeInfo=employees.get(0);
    	if(employeeInfo.getUserCode().equals(userCode)){
    		return true;
    	}
        return false;
    }

    


    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2011-10-18
     * @see com.cap.bts.dms.dm.employeemgnt.service.IMaintainDealerEmployeeService#resetpassword(java.lang.String, com.cap.bts.framework.usermgnt.domain.User)
    **/
    @Override
    public void resetpassword(String userCode, User currentUser) throws AppException {
      
        User user = userMgntService.getUserByUserCode(userCode);
        String password = PasswordUtil.getRandom();
        user.setPassword(PasswordUtil.encodePassword(password));
        user.setLastUpdateBy(currentUser.getId());
        user.setLastUpdateDate(new Date());
        userMgntService.updateUser(user);
        
        Long mobile = resetPasswordService.getUserMobilePhone(userCode);
        if (mobile != null) {
        	resetPasswordService.sendMessage(user, password, mobile);
        }
    }


	
	/**
	 * 查看是否能自动移交工作,销售顾问，客服，电话销售顾问不能自动移交
	 * @Date        :      2011-11-12
	 * @param user
	 * @return
	 */
	private boolean canAutoWorkTransfer(User user) {
	    boolean result = true;
	    if (user == null || user.getUserGroup() == null) {
	        return result;
	    }
	    if (UserGroupCode.SALECONSULTANT.getValue().equals(user.getUserGroup().getUserGroupCode()) 
	        || UserGroupCode.TELESALESPERSON.getValue().equals(user.getUserGroup().getUserGroupCode()) 
	        || UserGroupCode.SERVICEREP.getValue().equals(user.getUserGroup().getUserGroupCode())) {
	        result = false;
	    }
	    return result;
	}



	@Override
	public void approveUserGroupApplication(ApprovalSubmitDto submitDto) throws AppException {
		UserAccountApprovalDto dto=new UserAccountApprovalDto();
		dto.setUserCode(submitDto.getUserCode());
		dto.setUserGroupCode(submitDto.getUserGroupCode());
		dto.setAppResult(submitDto.getAppResult());
		dto.setOrgCode(submitDto.getOrgCode());
		dto.setEmploymentStatus(submitDto.getEmploymentStatus());
		syncEmployeeByApprovalResult(dto,1);
		
	}



}
